/*
 * @lc app=leetcode.cn id=501 lang=cpp
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
    void dfs(TreeNode* root, map<int, int>& m)
    {
        if(root != nullptr)
        {
            m[root->val]++;
            dfs(root->left, m);
            dfs(root->right, m);
        }
    }
class Solution {
public:
    vector<int> findMode(TreeNode* root) {
        map<int, int> m;
        dfs(root, m);

        int cnt = 0;
        for(auto& p : m)
        {
            cnt = std::max(cnt, p.second);
        }
        vector<int> ans;
        for(auto& p : m)
        {
            if(p.second == cnt)
            {
                ans.push_back(p.first);
            }
        }
        return ans;
    }
};
// @lc code=end

